package com.loong.common.mongo.file;

import com.loong.common.exception.GlobalException;
import com.loong.common.mongo.utils.MongoFileIdUtils;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSDownloadStream;
import com.mongodb.client.gridfs.model.GridFSFile;
import lombok.extern.slf4j.Slf4j;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.gridfs.GridFsResource;
import org.springframework.data.mongodb.gridfs.GridFsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.io.ByteArrayInputStream;

@Slf4j
@Service
public class MongoFileService {

    @Autowired
    private GridFsTemplate gridFsTemplate;
    @Resource
    private GridFSBucket gridFSBucket;

    /**
     * 获取文件路径
     *
     * @param fileId
     * @param isBackend
     * @return
     */
    public String getFilePath(final String fileId, final boolean isBackend) {
        if (isBackend) {
            return "/api/manage/system/file/get/" + fileId;
        } else {
            return "/api/forehead/system/file/get/" + fileId;
        }
    }

    /**
     * 获取下载文件路径
     *
     * @param fileId
     * @param isBackend
     * @return
     */
    public String getDownloadFilePath(final String fileId, final boolean isBackend) {
        if (isBackend) {
            return "/api/manage/system/file/download/" + fileId;
        } else {
            return "/api/forehead/system/file/download/" + fileId;
        }
    }


    /**
     * 删除文件
     *
     * @param id
     */
    public void delete(String id) {
        id = MongoFileIdUtils.getReallyId(id);
        gridFsTemplate.delete(Query.query(Criteria.where("_id").is(id)));
    }

    /**
     * 获取文件
     *
     * @param id
     * @return
     */
    public GridFsResource get(String id) {
        id = MongoFileIdUtils.getReallyId(id);
        GridFSFile gridFSFile = gridFsTemplate.findOne(Query.query(Criteria.where("_id").is(id)));
        GridFSDownloadStream downloadStream = gridFSBucket.openDownloadStream(gridFSFile.getObjectId());
        GridFsResource gridFsResource = new GridFsResource(gridFSFile, downloadStream);
        return gridFsResource;
    }

    /**
     * 保存文件
     *
     * @param mongoFileDO
     * @return
     * @throws GlobalException
     */
    public String save(MongoFileDO mongoFileDO) throws GlobalException {
        if (ObjectUtils.isEmpty(mongoFileDO)) {
            return null;
        }
        try(ByteArrayInputStream inputStream = new ByteArrayInputStream(mongoFileDO.getData())) {
            ObjectId objectId = gridFsTemplate.store(inputStream, mongoFileDO.getFileName(), mongoFileDO.getContentType());
            if (ObjectUtils.isEmpty(objectId)) {
                return null;
            }
            return objectId.toString();
        } catch (Exception e) {
            log.info("MongoFileService.save() error", e);
            throw new GlobalException("保存文件到MongoDB出现错误" ,e);
        }
    }
    /**
     *
     * @param zipFile
     * @return
     * @throws GlobalException
     */
	public String save(File zipFile) throws GlobalException {
		try (ByteArrayInputStream inputStream = new ByteArrayInputStream(zipFile.getContent())) {
			ObjectId objectId = gridFsTemplate.store(inputStream, zipFile.getName(), zipFile.getContentType());
			if (ObjectUtils.isEmpty(objectId)) {
				return null;
			}
			return objectId.toString();
		} catch (Exception e) {
			log.info("MongoFileService.save() error", e);
			throw new GlobalException("保存文件到MongoDB出现错误", e);
		}
	}
}
